
angular.module('avoidMistakes.controllers', [])

    .controller('HomeCtrl', ['$scope', '$ionicModal', 'HomeService', '$ionicPopup','$cordovaToast',
        function ($scope, $ionicModal, HomeService, $ionicPopup, $cordovaToast) {
            //所有串口号
            $scope.ports = [];
            var num = 1;
            $scope.data = {
            	//选择的串口
			    selectPort: '',
			    //芯片id
			    chipId:'',
			    //车型
			    car:'',
			    carImage:'',
			    //用户
			    user:'',
			    //头像
			    userImage:''

			};
			var orderId = 1;
			//芯片ID,废品订单标识,订单ID,喷码内容,取货口,用户名称
			// var chipData = "123456789|0|1|XXXXXX|北京|张三";
			var chipData = "31 32 33 34 35 36 7C 30 7C 31 36 30 37 32 30 30 30 30 30 38 7C";
		
             
			$ionicModal.fromTemplateUrl('tpls/setting.html', {
	            scope: $scope,
	            animation: 'slide-in-right'
	        }).then(function(modal) {
	            $scope.modal = modal;
	        });

           

	        //网络获取订单数据
            function getOrderData(orderId){
				HomeService.getOrderData(orderId).then(function(data){
				   $scope.data.car = data.data.product_name;
				   $scope.data.user = data.data.user_nickname;
				   $scope.data.userImage = data.data.user_avatar;
				   $scope.data.carImage = data.data.product_image;
				},function(error){
				   $cordovaToast.showShortBottom(error);
				});
            }
            //获取当前订单数据
            function getCurrentOrderData(){
				HomeService.getCurrentOrderData().then(function(data){
				   $scope.data.car = data.data.product_name;
				   $scope.data.user = data.data.user_nickname;
				   $scope.data.userImage = data.data.user_avatar;
				   $scope.data.carImage = data.data.product_image;
				},function(error){
				   $cordovaToast.showShortBottom(error);
				});
            }
            //获取芯片数据
            function getChipData(data){
                var chip_data = data.split("7C");
                // $scope.data.chipId = chip_data[0];
                // var orderId = parseInt(chip_data[2]);
                var chip_id_data = chip_data[0].split(" ");
                for (var i = 0; i < chip_id_data.length-1; i++) {
                     $scope.data.chipId = $scope.data.chipId + String.fromCharCode(parseInt(chip_id_data[i],16));
                }

                var order_data = chip_data[2].split(" ");
                var order_id = '';
                for (var i = 1; i < order_data.length-1; i++) {
                     order_id = order_id + String.fromCharCode(parseInt(order_data[i],16));
                }

                // getOrderData(order_id);
                getCurrentOrderData();
                   
            }  

            // getChipData(chipData);
            
            // window.localStorage.setItem("port", angular.toJson("/dev/ttymxc1"));


            document.addEventListener("deviceready", function() {
            	if (cordova.plugins.SerialPort) {
            		var port = angular.fromJson(window.localStorage.getItem("port"));
            		$cordovaToast.showShortBottom(port);
            		if (port == null) {
                        $scope.$on('serialport.DataReceived', function (e, data) {
                        	 $cordovaToast.showShortBottom(data);
					         if(data){
					         	if(num===1){
						         	window.localStorage.setItem("port", angular.toJson($scope.data.selectPort));
						      //    	$ionicPopup.alert({
								    //    title: '串口设置成功',
								    //    template: '无需设置'
								    // });
								    getChipData(data);
								    
								    num++;
					         	}else{
					         		getChipData(data);   
					         	}
					         	
					         }
					         else{
					         	cordova.plugins.SerialPort.close();
					         }    
					    });

            		}
            		else{
         //    			$ionicPopup.alert({
					    //    title: '串口设置成功',
					    //    template: '无需设置'
					    // });
            			$scope.data.selectPort = port;
            			cordova.plugins.SerialPort.open($scope.data.selectPort, {}, function () {
				        
		                }, function () {
		                	$cordovaToast.showShortBottom("打开串口失败");
		                	
		                });
		                $scope.$on('serialport.DataReceived', function (e, data) {
		                	$cordovaToast.showShortBottom(data);
		                	
					        getChipData(data);
							 
					    });
            		}
            		
	                
            	}
                
			}, false);
	        

	        $scope.showPorts = function(){
	        	

             //    $scope.modal.show().then(function () {

             //        $scope.ports = [{
             //        	path:'/dev/ttymxc1'
             //        },
             //        {
             //        	path:'/dev/ttymxc2'
             //        },
             //        {
             //        	path:'/dev/ttymxc3'
             //        },
             //        {
             //        	path:'/dev/ttymxc4'
             //        }];
					    
	            // });

				if (cordova.plugins.SerialPort) {
					cordova.plugins.SerialPort.getAllDevices(function(ports) {
					    $scope.ports = ports;
					    $scope.modal.show().then(function () {
			                // $scope.$apply();
			            });
					    
					}, function(error) {
						$cordovaToast.showShortBottom("获取设备的端口号失败"+error);
					    
					});
				}	
	        };

	        $scope.getOnePort = function(port){

			    $scope.data.selectPort  =  port;
			   
	            cordova.plugins.SerialPort.open(port, {}, function () {
			        	
		        	$scope.modal.hide();
                }, function () {
                	$cordovaToast.showShortBottom("打开串口失败");
                	
                });
	        };

	        $scope.$on('$ionicView.afterLeave', function() {
                cordova.plugins.SerialPort.close();
            });

	        
        }

    ]);